import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { router } from 'umi';
import { Button, Form } from 'antd';
import ManageList from '@/components/ManageList';
import StandardTable from '@/components/StandardTable';
import TableButtons from '@/components/TableButtons';
import SelectForm from '@/components/SelectForm';
import AntdFormItem from '@/components/AntdFormItem';
import AntdInput from '@/components/AntdInput';
import RightDraw from '@/components/RightDraw';
import DistributionDetail from './DistributionDetail';
import AdButton from '@/components/AdButton';
import { codes } from './utils';

let globalListData = [];
@ManageList
@connect(({ distribution, loading }) => ({
  distributionList: distribution.distributionList,
  // distributionDetail: distribution.distributionDetail,
  loading: loading.effects['distribution/selectFirstDistribution'],
}))
@Form.create()
export default class DistributionList extends Component {
  state = {
    selectedRows: [],
    formValues: {},
    expandForm: false,
    isAbled: '',
    checkId: '',
    visibleFile: false,
  };
  className = 'DistributionList';

  componentDidMount() {
    this.selectDistributionList();
  }

  selectDistributionList = (params = {}, type) => {
    const { dispatch } = this.props;
    const { id } = params;
    if (id) params.id = id;
    dispatch({
      type: 'distribution/selectFirstDistribution',
      payload: params,
      callback: res => {
        res.map(v => {
          if (v.childNumber > 0) v.children = [];
        });
        if (type === 'child') {
          this.locationData(res, globalListData, id);
        } else {
          globalListData = res;
        }
      },
    });
  };
  /*
  层级结构：
  */
  locationData = (dataChild, data, id) => {
    data.forEach(v => {
      // if (dataChild.length > 0 && v.children.length === 0 && v.id == id) {
      if (dataChild.length > 0 && v.id == id) {
        v.children = dataChild;
      } else if (v.children) {
        this.locationData(dataChild, v.children, id);
      }
    });
  };
  //展开关闭：
  onExpandRow = (expanded, record) => {
    // console.log('expanded, record', expanded, record);
    expanded && this.selectDistributionList({ id: record.id }, 'child');
  };

  /**
   * form 查找条件 展开 收起
   */
  toggleForm = expandForm => {
    this.setState({
      expandForm,
    });
  };

  /**
   * form 查找条件 重置
   */
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    this.selectDistributionList();
  };

  /**
   * form 查找条件 查询
   */
  handleSearch = formValues => {
    if (!formValues) return;
    this.setState({
      formValues,
    });
    this.selectDistributionList({ payload: formValues });
  };

  /**
   * table 表格 批量选择
   */
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  /**
   * table 表格 分页操作
   */
  handleStandardTableChange = param => {
    const { formValues } = this.state;
    this.selectDistributionList({ payload: { ...formValues, ...param } });
  };

  handleAdd = () => {
    router.push('/roadNetwork/DistributionList/DistributionAdd');
  };

  columns = [
    {
      title: '名称',
      dataIndex: 'name',
      render: (text, record) => (
        // <a onClick={() => this.showDetail(record)} title={text}>
        //   {text}
        // </a>
        <AdButton
          mode="a"
          onClick={e => this.showDetail(e, record)}
          text={text}
          title={text}
          code={codes.showDetail}
        />
      ),
      width: 200,
    },
    {
      title: '地址全路径',
      dataIndex: 'fullName',
      width: 250,
    },
    {
      title: '关键字',
      dataIndex: 'keyWords',
      width: 250,
    },
    {
      title: '层级',
      dataIndex: 'level',
      width: 100,
    },

    {
      title: '排序号',
      dataIndex: 'sort',
      width: 100,
    },
    {
      title: '是否有效',
      dataIndex: 'beActive',
      render: text => <span>{text ? '有效' : '无效'}</span>,
    },
  ];
  //详情：
  showDetail = (e, record) => {
    e.stopPropagation();
    const { dispatch } = this.props;
    const { id } = record;
    dispatch({
      type: 'distribution/distributionDetail',
      payload: { id },
      callback: res => {
        this.setState(
          {
            checkId: id,
            rowDetails: record,
            isAbled: res.beActive == true || res.beActive == '启用' ? true : false,
          },
          () => {
            this.setState({
              visible: true,
            });
          }
        );
      },
    });
  };

  closeDetail = () => {
    this.setState({
      visible: false,
    });
  };
  //启用、禁用：
  abledStatus = (type, isSingle) => {
    const { dispatch } = this.props;
    const { selectedRows, checkId, formValues } = this.state;

    let params = {};
    if (isSingle) {
      params.ids = [checkId];
    } else {
      let ids = [];
      if (Array.isArray(selectedRows) && selectedRows.length > 0) {
        selectedRows.map((item, i) => {
          ids.push(item.id);
        });
      }
      params.ids = ids;
    }
    params.type = type == 'abled' ? true : false;
    dispatch({
      type: 'distribution/ableOperate',
      payload: params,
      callback: res => {
        if (isSingle) {
          this.props.dispatch({
            type: 'distribution/distributionDetail',
            payload: { id: checkId },
            callback: res => {
              this.setState({
                isAbled: res.beActive == true || res.beActive == '启用' ? true : false,
              });
            },
          });
        } else {
          this.selectDistributionList({ payload: formValues });
        }
      },
    });
  };
  //编辑：
  handleEdit = () => {
    console.log('编辑');
    router.push(`/roadNetwork/DistributionList/DistributionEdit/${this.state.checkId}`);
    this.closeDetail();
  };
  //删除
  delRecord = e => {
    e.stopPropagation();
    const {
      dispatch,
      abnormal: { id },
      match: { params },
    } = this.props;
    const { selectedRows, selectedRowsPay } = this.state;
    let ids = selectedRows.map(v => v.id);
    dispatch({
      type: 'distribution/deleteDistribution',
      payload: { ids },
      callback: () => {
        this.selectDistributionList();
      },
    });
  };
  render() {
    const {
      distributionList,
      loading,
      form: { getFieldDecorator },
      isMobile,
    } = this.props;
    const { selectedRows, expandForm, isAbled, visible, checkId, visibleFile } = this.state;
    const commonParams = {
      getFieldDecorator,
    };
    const firstFormItem = (
      <AntdFormItem label="名称" code="name" {...commonParams}>
        <AntdInput />
      </AntdFormItem>
    );
    // 查询条件 参数
    const selectFormParams = {
      firstFormItem,
      form: this.props.form,
      code: codes.select,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: this.toggleForm,
    };
    const rightDrawParams = {
      isMobile,
      visible,
      title: '配送区域详情',
      closeDetail: this.closeDetail,
      code: codes.showDetail,
      buttons: (
        <span>
          <Button.Group>
            {isAbled && (
              <AdButton
                onClick={() => this.abledStatus('disabled', 1)}
                text="禁用"
                code={codes.disable}
              />
            )}
            {!isAbled && (
              <AdButton
                onClick={() => this.abledStatus('abled', 1)}
                text="启用"
                code={codes.enable}
              />
            )}
            <AdButton type="primary" onClick={this.handleEdit} text="编辑" code={codes.edit} />
          </Button.Group>
        </span>
      ),
    };
    // 表格按钮 参数
    const tableButtonsParams = {
      buttons: (
        <Button.Group>
          <AdButton
            onClick={() => this.abledStatus('abled')}
            disabled={selectedRows.length > 0 ? false : true}
            text="启用"
            code={codes.enable}
          />
          <AdButton
            onClick={() => this.abledStatus('disabled')}
            disabled={selectedRows.length > 0 ? false : true}
            text="禁用"
            code={codes.disable}
          />

          {/* <Button
          {{ marginLeft: 8 }}
            type="danger"
            onClick={e => this.delRecord(e)}
            disabled={selectedRows.length > 0 ? false : true}
          >
            删除
          </Button.Group> */}
        </Button.Group>
      ),
      handleAdd: this.handleAdd,
      code: codes.add,
    };
    // console.log('===========', globalListData);
    return (
      <Fragment>
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        <StandardTable
          selectedRows={selectedRows}
          loading={loading}
          // data={distributionList}
          data={{ list: globalListData }}
          columns={this.columns}
          onSelectRow={this.handleSelectRows}
          onPaginationChange={this.handleStandardTableChange}
          scrollX={1100}
          expandForm={expandForm}
          className={this.className}
          onExpandRow={this.onExpandRow}
        />
        {visible && (
          <RightDraw {...rightDrawParams}>
            <DistributionDetail detailId={checkId} isMobile={isMobile} />
          </RightDraw>
        )}
      </Fragment>
    );
  }
}
